package cn.sc.summer.log.util;

import cn.hutool.core.util.ObjectUtil;
import cn.sc.summer.exception.exceptions.CommonException;
import org.aspectj.lang.JoinPoint;
import org.springframework.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类名：日志解析工具类
 *
 * @author a-xin
 * @date 2024/2/7 16:02
 */
public class LogUtil {

    /**
     * 根据切点和请求体获取请求参数
     *
     * @param request   请求体
     * @param joinPoint 切点
     * @return 请求包含的参数信息
     */
    public static Map<String, String> getParams(HttpServletRequest request, JoinPoint joinPoint) {
        Map<String, String> parameterMap = new HashMap<>();
        if (HttpMethod.POST.name().equals(request.getMethod())) {
            Object[] args = joinPoint.getArgs();
            if (ObjectUtil.isNotEmpty(args)) {
                Object object = args[0];
                if (ObjectUtil.isNotNull(object)) {
                    Class<?> userCla = object.getClass();
                    Field[] superFields = userCla.getSuperclass().getDeclaredFields();
                    /* 得到类中的所有属性集合 */
                    Field[] fields = userCla.getDeclaredFields();
                    List<Field> collect = Arrays.stream(fields).collect(Collectors.toList());
                    collect.addAll(Arrays.stream(superFields).collect(Collectors.toList()));
                    for (Field field : collect) {
                        if (ObjectUtil.isNotNull(field)) {
                            field.setAccessible(true);
                            try {
                                Optional.ofNullable(field.get(object)).ifPresent(value -> {
                                    if (!field.getName().equals("serialVersionUID")) {
                                        parameterMap.put(field.getName(), value.toString());
                                    }
                                });
                            } catch (Exception e) {
                                throw new CommonException(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
        } else {
            Map<String, String[]> parameterMap1 = request.getParameterMap();
            parameterMap1.forEach((key, value) -> {
                if (value.length <= 1) {
                    parameterMap.put(key, value[0]);
                } else {
                    parameterMap.put(key, Arrays.toString(value));
                }
            });
        }
        return parameterMap;
    }

}
